<template>
  <div class="client-nursing-container">
    <h2 class="title">客户护理设置</h2>

    <!-- 查询表单 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <div class="search-left">
        <el-form-item label="客户名:">
          <el-input v-model="searchForm.name" placeholder="请输入客户名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
      </div>
      <div class="search-right">
        <el-button type="success" @click="openCreateDialog">新建</el-button>
      </div>
    </el-form>


    <el-table :data="tableData" v-loading="loading" border style="width: 100%; background: #f5f7fa;"
      :header-cell-style="{ background: '#f9fafc', color: '#333', textAlign: 'center' }"
      :cell-style="{ textAlign: 'center' }">
      <el-table-column prop="client.name" label="客户名" />
      <el-table-column prop="client.gender" label="性别" />
      <el-table-column prop="client.age" label="年龄" />
      <el-table-column prop="client.phone" label="电话" />
      <el-table-column prop="nursingLevel.levelName" label="护理级别" />
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <el-button type="danger" size="small" @click="remove(scope.row)">删除</el-button>
          <el-button type="primary" size="small" @click="viewRecord(scope.row.client.clientId)">查看护理记录</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-bar">
      <el-pagination v-model:current-page="pagination.cur" v-model:page-size="pagination.size" :total="pagination.total"
        :page-sizes="[5, 10, 20]" layout="total, sizes, prev, pager, next, jumper" @current-change="handleCurrentChange"
        @size-change="handleSizeChange" />
    </div>

    <ClientSelectorDialog ref="createDialogRef" @closeAndRefresh="handleSearch" />
    <NursingRecordTable ref="recordRef" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { inject } from 'vue'
const axios = inject("axios")

import { ElMessage } from 'element-plus'
import ClientSelectorDialog from '@/components/nursing/clientNursing/ClientSelectorDialog.vue'
import NursingRecordTable from '@/components/nursing/clientNursing/NursingRecordTable.vue'
import { ElMessageBox } from 'element-plus'

const searchForm = ref({ name: '' })
const tableData = ref([])
const loading = ref(false)
const pagination = ref({ cur: 1, size: 5, total: 0 })

const recordRef = ref()
const createDialogRef = ref()

const handleSearch = () => {
  pagination.value.cur = 1
  query(1)
}

const query = async (page) => {
  loading.value = true
  try {
    const res = await axios.get('/clientNursingProject/pageClientAndLevel', {
      params: {
        cur: page,
        number: pagination.value.size,
        name: searchForm.value.name
      }
    })
    if (res.data.status === 200) {
      tableData.value = res.data.data || []
      pagination.value.total = res.data.total || 0
    } else {
      ElMessage.warning(res.data.msg || '查询失败')
    }
  } finally {
    loading.value = false
  }
}

const handleCurrentChange = (page) => {
  pagination.value.cur = page
  query(page)
}
const handleSizeChange = (size) => {
  pagination.value.size = size
  pagination.value.cur = 1
  query(1)
}

const remove = async (row) => {
  const clientId = row.client?.clientId
  const levelId = row.nursingLevel?.levelId
  if (!clientId || !levelId) {
    ElMessage.warning('缺少客户端或护理等级ID，无法删除')
    return
  }

  try {
    await ElMessageBox.confirm(
      `
      <div style="font-size: 16px; line-height: 1.8; padding: 5px 0;">
        是否确认<strong style="color: #f56c6c;">删除该护理配置</strong>？
        <br />
        <span style="color: #909399;">注意：删除后将 <strong style="color: red;">无法恢复</strong>。</span>
      </div>
    `,
      '操作确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消操作',
        dangerouslyUseHTMLString: true,
        type: 'warning',
        center: true,
        showClose: false,
        customClass: 'confirm-dialog-custom'
      }
    )

    const res = await axios.post('/clientNursingProject/deleteClientNursingProject', null, {
      params: { clientId, levelId }
    })

    if (res.data.status === 200) {
      ElMessage.success('删除成功')
      query(pagination.value.cur)
    } else {
      ElMessage.warning(res.data.msg || '删除失败')
    }

  } catch (error) {
    // 只提示真正的异常，不提示取消
    if (error !== 'cancel' && error !== 'close') {
      ElMessage.error('删除请求出错：' + error.message)
    }
    // 否则安静取消
  }
}


const viewRecord = (clientId) => {
  recordRef.value.open(clientId)
}
const openCreateDialog = () => {
  createDialogRef.value.open()
}

onMounted(() => {
  query(1)
})
</script>

<style scoped>
.client-nursing-container {
  padding: 20px;
}

.title {
  font-size: 27.2px;
  font-weight: bold;
  margin: 0 0 20px 0;
  color: #333;
}

.search-form {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  margin-bottom: 20px;
}

.search-left {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.search-right {
  display: flex;
  align-items: center;
}


.pagination-bar {
  display: flex;
  justify-content: flex-end;
  margin-top: 2%;
  margin-bottom: 2%;
}
</style>
